package com.biostime.qdingding.modules.qd.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ListResponse;
import com.biostime.qdingding.common.api.ObjResponse;
import com.biostime.qdingding.common.utils.QrCodeUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.api.dto.ButtonDto;
import com.biostime.qdingding.modules.qd.api.dto.CommentDto;
import com.biostime.qdingding.modules.qd.api.dto.CourseDetailDto;
import com.biostime.qdingding.modules.qd.api.dto.DiscountDto;
import com.biostime.qdingding.modules.qd.api.dto.OrderNewsDto;
import com.biostime.qdingding.modules.qd.entity.Album;
import com.biostime.qdingding.modules.qd.entity.Coupon;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Courseprice;
import com.biostime.qdingding.modules.qd.entity.Promotion;
import com.biostime.qdingding.modules.qd.service.AlbumService;
import com.biostime.qdingding.modules.qd.service.CommentService;
import com.biostime.qdingding.modules.qd.service.CouponService;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.CourseService;
import com.biostime.qdingding.modules.qd.service.CoursepriceService;
import com.biostime.qdingding.modules.qd.service.ParentGuidanceService;
import com.biostime.qdingding.modules.qd.service.PriceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


/**
 * 课程详情
 * 
 * @author chenweicheng
 * @version 2015-11-09
 */
@RestController
@RequestMapping(value = "${adminPath}/qd/api/courseDetail")
public class CourseDetailApi extends BaseController {

	@Autowired
	private CourseService courseService;

	@Autowired
	private CourseOrderService orderService;

	@Autowired
	private CommentService commentService;

	@Autowired
	private AlbumService albumService;
	
	@Autowired
	private CoursepriceService priceService;
	
	@Autowired
	private PriceService moneyService;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired ParentGuidanceService parentGuidanceService;
			
	/**
	 * 课程详情/获取课程评论人的头像和总数 
	 * @return 
	 */
	@RequestMapping(value = "getImageAndCount")
	public ObjResponse<HashMap<String,Object>> getImageAndCount(String courseId,String type) {
		String message = null;
		int errCode = 0;
		HashMap<String,Object>  map = new HashMap<String,Object>();
		Course course = null;
		
		if(courseId != null && type != null){
			course = courseService.apiGetInOrOut(type, courseId);
			if(course != null){			
				String serialId =String.valueOf(course.getSerialId());
				String levelId =String.valueOf(course.getLevelId());
				List<String>  imageList = commentService.apiGetHeadImage(serialId, levelId);
				int count = commentService.apiGetCommentNum(serialId,levelId);
				map.put("imageList", imageList);
				map.put("count", count);
				message = "查询成功";
				errCode = 0;				
			}else{
				message = "查询失败,课程不存在";
				errCode = 1;				
			}

		}else{
			message = "查询失败,参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj(map);
	}
		
	/**
	 * 课程详情/课程评论列表
	 * 默认页数为1，条数为10
	 * @return
	 */
	@RequestMapping(value = "getCourseComments")
	public ListResponse<CommentDto> getCommentList(HttpServletRequest request) {
		// 默认页数为1，条数为10
		int pageindex = 1;
		int pagesize = 10;
		String message = null;
		String category = null;
		CommentDto commentDto = null;
		List<Album> albumList = null;
		Course course = null;
		String imageUrl = null;
		int errCode = 0;
		String userId = request.getParameter("userId");
		String courseId = request.getParameter("courseId");
		String type = request.getParameter("type");
		List<CommentDto> commentList = new ArrayList<CommentDto>();
		List<CommentDto> commentList2 = new ArrayList<CommentDto>();		

		if (request.getParameter("pageindex") != null && request.getParameter("pageindex") != null) {
			pageindex = Integer.parseInt(request.getParameter("pageindex"));
			pagesize = Integer.parseInt(request.getParameter("pagesize"));
		}
		
		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, "NOT-NULL", userId, type, "NOT-NULL");
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");
		if (flag) {
			course = courseService.apiGetInOrOut(type, courseId);
			
			//获取课程评论列表
			if (course != null) {
				PageHelper.startPage(pageindex, pagesize);
				commentList = commentService.apiGetCommentList(String.valueOf(course.getSerialId()),String.valueOf(course.getLevelId()),userId);
				if (course.getType() == 0) {
					category = "courseComment";
				} else {
					category = "outcourseComment";
				}
			}
			
			//将commentList，与之对应的图片放进commentDto内
			for (int i = 0; i < commentList.size(); i++) {
				commentDto = commentList.get(i);
				albumList = albumService.apiGet(category, String.valueOf(commentDto.getId()));
				if(!albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).isEmpty()){
					imageUrl = albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).get(0).getThumbPath();
				}
				commentDto.setHeadImg((imageUrl)); 
				commentDto.setImages(albumList);
				commentList2.add(commentDto);
			}
			
			message = "查看课程评论列表成功";
			errCode = 0;
		} else {
			message = "查看课程评论列表失败，"+checkMessage;
			errCode = 1;
		}

		PageInfo<CommentDto> page = new PageInfo<CommentDto>(commentList);

		return FastResponse.create().errCode(errCode).subCode(0).errMsg(message).pageIndex(page.getPageNum())
				.pageSize(page.getPageSize()).total((int) page.getTotal()).hasNext(page.isHasNextPage())
				.list(commentList2);
	}

	/**
	 * 课程详情/获取课程信息详情
	 * @return
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@RequestMapping(value = "getCourseDetail")
	public ObjResponse<CourseDetailDto> getCourseDetail(HttpServletRequest request) throws Exception {
		int errCode = 0;
		String category = null;
		CourseDetailDto courseDetail = null; 
		HashMap<String, Object> hashMap = null;
		String message = null;
		String userId = request.getParameter("userId");
		String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String centerId = request.getParameter("centerId");
		List<Album> albumList = null;
		Course course = null;
		List<Courseprice>  priceList = null;	
		List<DiscountDto>  discountDtoList = new ArrayList<DiscountDto>();; 
		List<Promotion> promotionList = new ArrayList<Promotion>();
		List<HashMap<String,Object>>  promotionIdMap = null;
		Double moneyBefore = 0.0;
		double moneyAfter = 0.0;
		int freeDiscountId = 0;
		
		// 参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, type, centerId);
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");

		if (flag == true) {
			course = courseService.apiGetInOrOut(type, courseId);
			if (course != null) {
				
				//判断courseDetail是否存在
				courseDetail = courseService.apiGetCourseDetail(courseId, studentId ,type);				
				if(courseDetail !=null ){
					
					//获取courseDetail的状态，如果为已预约，则获取预约排名
					if (courseDetail.getState() != null) {
						if(courseDetail.getState().equals("ordered")){
							// 我的课程排名
							BigDecimal courseOrder = (BigDecimal) orderService.apiCourseOrder(courseId, studentId, type)
									.get("RANK");
							courseDetail.setCourseOrder(courseOrder);							
						}else{
							courseDetail.setCourseOrder(new BigDecimal(0));
						}
					}else{
						courseDetail.setCourseOrder(new BigDecimal(0));
					}
					
					//课程预约人数 			
					int courseBook = orderService.apiCourseBook(courseId, type);
					
					// 课程排位人数
					int courseQueue = orderService.apiCourseQueue(courseId, type);
					courseDetail.setCourseBook(courseBook);
					courseDetail.setCourseQueue(courseQueue);

					//获取课程图片列表
					if (type.equals("0")) {
						category = "course";
					} else {
						category = "outcourse";
					}
					albumList = albumService.apiGet(category, String.valueOf(courseId));
					courseDetail.setCourseImages(albumList);

					//获取课程评分
					hashMap = commentService.apiScoreByTheme(String.valueOf(course.getSerialId()),String.valueOf(course.getLevelId()));
					if (hashMap != null) {
						courseDetail.setEnvironmentCommentStar((BigDecimal) hashMap.get("ENVSCORE"));
						courseDetail.setTeacherCommentStar((BigDecimal) hashMap.get("TEACHERSCORE"));
						courseDetail.setTotalCommentStar((BigDecimal) hashMap.get("SCORE"));
					}
					
					//获取统一忙时价格
					double initPrice = 0;
					if(!priceService.apiGetPrice(0, centerId).isEmpty()){
						 initPrice = priceService.apiGetPrice(0, centerId).get(0).getPrice();	
						 initPrice=moneyService.changeMoney(initPrice);
					}
					int priceType = course.getPriceType();
					HashMap<String,Object> priceMap = moneyService.getPriceMap(course, studentId);
					if(priceMap != null){
						moneyBefore = (double) priceMap.get("moneyBefore");
						moneyAfter = (double) priceMap.get("moneyAfter");
						freeDiscountId = (int) priceMap.get("freeDiscountId");
						promotionList = (List<Promotion>) priceMap.get("promotionList");
						priceList = (List<Courseprice>) priceMap.get("priceList");					
					}
					
					//遍历促销列表
					if(promotionList !=null ){
						for(int i=0;i<promotionList.size();i++){
							DiscountDto discountDto = null;
							Promotion promotion = promotionList.get(i); 
							if(promotion.getPromotionName() != null){
								discountDto = new DiscountDto();
								discountDto.setId(Integer.parseInt(promotion.getId()));
								discountDto.setName(promotion.getPromotionName());  
								discountDto.setDescription(promotion.getName()); 
								discountDtoList.add(discountDto);									
							}					
						}									
											
					}
					
					//设置时间类型，闲时还是忙时
					courseDetail.setTimeType(priceType);
					
					//设置优惠前价格
					if(priceType ==0 ){
						courseDetail.setMoneyBefore(moneyBefore);
					}else{
						courseDetail.setMoneyBefore(initPrice);
					}
					
					//设置优惠后价格
					courseDetail.setMoneyAfter(moneyAfter); 
					
					//如果studentId为0
					if(studentId.equals(String.valueOf(BasicApi.defaultStudentId))){
						courseDetail.setMoneyAfter(courseDetail.getMoneyBefore()); 
					}
					
					//设置优惠列表
					courseDetail.setDiscounts(discountDtoList); 
					
					//设置闲时优惠列表
					if(priceType == 0){
						courseDetail.setFreeTimeDisccounts(null);	
					}else{
						courseDetail.setFreeTimeDisccounts(priceList);					
					}
					
					//根据预约排名设置当时闲时优惠列表id
					courseDetail.setFreeDiscountId(freeDiscountId); 
					
					//设置签到二维码图片
					if(orderService.apiGetOrderId(courseId,type,studentId) != null){
						BigDecimal  orderId = (BigDecimal ) orderService.apiGetOrderId(courseId,type,studentId).get("ID");
						String url = QrCodeUtils.getCode(String.valueOf(orderId),300, 300, orderId+".png");
						courseDetail.setUrl(url);  
											
					}
					//设户外课程的系列为户外课程
					if(courseDetail.getType().equals("1")){
						courseDetail.setSerial("户外课程");
					} 
					
					//如果状态为canceled，则返回null
					if(courseDetail.getState() != null && courseDetail.getState().equals("canceled")){
						courseDetail.setState(null); 
					}
					
					//设置可用优惠券数码
					int couponNum = couponService.availableNum(userId, "%"+courseDetail.getType()+"%");
					courseDetail.setCouponNum(couponNum);
				}
								
				message = "获取课程信息详情成功";
				errCode = 0;
			} else {
				message = "获取课程信息详情失败，课程不存在";
				errCode = 1;
			}
		} else {
			message = "获取课程信息详情失败，"+checkMessage;
		}

		return FastResponse.create().errMsg(message).errCode(errCode).obj(courseDetail);
	}
	
	/**
	 * 课程详情/获取课程信息详情
	 * @version 2016-03-07
	 * @return
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@RequestMapping(value = "getCourseDetail_vesion2")
	public ObjResponse<CourseDetailDto> getCourseDetail_vesion2(HttpServletRequest request) throws Exception {
				
		int errCode = 0;
		String category = null;
		CourseDetailDto courseDetail = null; 
		HashMap<String, Object> hashMap = null;
		String message = null;
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String centerId = request.getParameter("centerId");
		List<Album> albumList = null;
		Course course = null;
		List<Courseprice>  priceList = null;	
		List<DiscountDto>  discountDtoList = new ArrayList<DiscountDto>();; 
		List<Promotion> promotionList = new ArrayList<Promotion>();
		List<HashMap<String,Object>>  promotionIdMap = null;
		Double moneyBefore = 0.0;
		double moneyAfter = 0.0;
		int freeDiscountId = 0;
		
		// 参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL", centerId);
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");

		if (flag == true) {
			course = courseService.apiGetInOrOut(null, courseId);
			if (course != null) {
				
				//判断courseDetail是否存在
				courseDetail = courseService.apiGetCourseDetail(courseId, studentId ,null);				
				if(courseDetail !=null ){
					
					//获取courseDetail的状态，如果为已预约，则获取预约排名
					if (courseDetail.getState() != null) {
						if(courseDetail.getState().equals("ordered")){
							// 我的课程排名
							BigDecimal courseOrder = (BigDecimal) orderService.apiCourseOrder(courseId, studentId, null)
									.get("RANK");
							courseDetail.setCourseOrder(courseOrder);							
						}else{
							courseDetail.setCourseOrder(new BigDecimal(0));
						}
					}else{
						courseDetail.setCourseOrder(new BigDecimal(0));
					}
					
					//课程预约人数 			
					int courseBook = orderService.apiCourseBook(courseId, null);
					
					// 课程排位人数
					int courseQueue = orderService.apiCourseQueue(courseId, null);
					courseDetail.setCourseBook(courseBook);
					courseDetail.setCourseQueue(courseQueue);

					//获取课程图片列表
					albumList = albumService.apiGet("course", String.valueOf(courseId));
					courseDetail.setCourseImages(albumList);

					//获取课程评分
					hashMap = commentService.apiScoreByTheme(String.valueOf(course.getSerialId()),String.valueOf(course.getLevelId()));
					if (hashMap != null) {
						courseDetail.setEnvironmentCommentStar((BigDecimal) hashMap.get("ENVSCORE"));
						courseDetail.setTeacherCommentStar((BigDecimal) hashMap.get("TEACHERSCORE"));
						courseDetail.setTotalCommentStar((BigDecimal) hashMap.get("SCORE"));
					}
					
					//获取统一忙时价格
					double initPrice = 0;
					if(!priceService.apiGetPrice(0, centerId).isEmpty()){
						 initPrice = priceService.apiGetPrice(0, centerId).get(0).getPrice();	
						 initPrice=moneyService.changeMoney(initPrice);
					}
					int priceType = course.getPriceType();
					HashMap<String,Object> priceMap = moneyService.getPriceMap(course, studentId);
					if(priceMap != null){
						moneyBefore = (double) priceMap.get("moneyBefore");
						moneyAfter = (double) priceMap.get("moneyAfter");
						freeDiscountId = (int) priceMap.get("freeDiscountId");
						promotionList = (List<Promotion>) priceMap.get("promotionList");
						priceList = (List<Courseprice>) priceMap.get("priceList");					
					}
					
					//遍历促销列表
					if(promotionList !=null ){
						for(int i=0;i<promotionList.size();i++){
							DiscountDto discountDto = null;
							Promotion promotion = promotionList.get(i); 
							if(promotion.getPromotionName() != null){
								discountDto = new DiscountDto();
								discountDto.setId(Integer.parseInt(promotion.getId()));
								discountDto.setName(promotion.getPromotionName());  
								discountDto.setDescription(promotion.getName()); 
								discountDtoList.add(discountDto);									
							}					
						}									
											
					}
					
					//设置时间类型，闲时还是忙时
					courseDetail.setTimeType(priceType);
					
					//设置优惠前价格
					if(priceType ==0 ){
						courseDetail.setMoneyBefore(moneyBefore);
					}else{
						courseDetail.setMoneyBefore(initPrice);
					}
					
					//设置优惠后价格
					courseDetail.setMoneyAfter(moneyAfter); 
					
					//如果studentId为0
					if(studentId.equals(String.valueOf(BasicApi.defaultStudentId))){
						courseDetail.setMoneyAfter(courseDetail.getMoneyBefore()); 
					}
					
					//设置优惠列表
					courseDetail.setDiscounts(discountDtoList); 
					
					//设置闲时优惠列表
					if(priceType == 0){
						courseDetail.setFreeTimeDisccounts(null);	
					}else{
						courseDetail.setFreeTimeDisccounts(priceList);					
					}
					
					//根据预约排名设置当时闲时优惠列表id
					courseDetail.setFreeDiscountId(freeDiscountId); 
					
					//设置签到二维码图片
					if(orderService.apiGetOrderId(courseId,null,studentId) != null){
						BigDecimal  orderId = (BigDecimal ) orderService.apiGetOrderId(courseId,null,studentId).get("ID");
						String url = QrCodeUtils.getCode(String.valueOf(orderId),300, 300, orderId+".png");
						courseDetail.setUrl(url);  
											
					}
					//设户外课程的系列为户外课程
					if(courseDetail.getType().equals("1")){
						courseDetail.setSerial("户外课程");
					} 
					
					//如果状态为canceled，则返回null
					if(courseDetail.getState() != null && courseDetail.getState().equals("canceled")){
						courseDetail.setState(null); 
					}
					
					//设置可用优惠券数码
					int couponNum = couponService.availableNum(userId, "%"+courseDetail.getType()+"%");
					if(courseDetail.getState() != null){ 
						couponNum = 0;
					}
					courseDetail.setCouponNum(couponNum);
					
					//设置是否显示按钮
					ButtonDto button = orderService.ifShowButton(courseDetail,studentId);
					courseDetail.setButton(button); 
					
					//设置优惠券id
					if(courseDetail.getCouponId().equals("0")){
						courseDetail.setCouponId(null); 
					}
					
					//设置父母指南url,如果课程状态为签到则显示
					String state = courseDetail.getState();
					if(state != null && state.equals("signed")){
						String serial = courseDetail.getSerial();
						String theme = courseDetail.getTheme();
						String clevel = courseDetail.getCourseLevel();
						String name = clevel+serial+theme;
						String url = parentGuidanceService.getParentGuidanceUrl(request, name);
						courseDetail.setParentGuidanceUrl(url);
					}
				}
								
				message = "获取课程信息详情成功";
				errCode = 0;
			} else {
				message = "获取课程信息详情失败，课程不存在";
				errCode = 1;
			}
		} else {
			message = "获取课程信息详情失败，"+checkMessage;
		}

		return FastResponse.create().errMsg(message).errCode(errCode).obj(courseDetail);
	}	
	
	/**
	 * 课程详情/获取指定课程的预约信息
	 * @return
	 */

	@SuppressWarnings({ "unchecked", "unused" })
	@RequestMapping(value = "getCourseOrder")
	public ObjResponse<OrderNewsDto> getCourseOrder(HttpServletRequest request) throws Exception{
		int errCode = 0;
		String message = null;
		String userId = request.getParameter("userId");
		String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String centerId = request.getParameter("centerId");
		String couponId = request.getParameter("couponId");
		OrderNewsDto newsDto = new OrderNewsDto();
		List<Courseprice>  priceList = null;	
		Double moneyBefore = 0.0;	
		Course course = null;
		List<DiscountDto>  discountDtoList = new ArrayList<DiscountDto>();; 
		List<Promotion> promotionList = new ArrayList<Promotion>();
		List<HashMap<String,Object>>  promotionIdMap = null;	
		HashMap<String,Object> freeMap = null;
		double moneyAfter = 0;
		
		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, type, centerId);
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");

		if (flag) {
			
			//通过id获取课程
			course = courseService.apiGetInOrOut(type, courseId);
			if(course != null){
				
				//课程预约人数
				int courseBook = orderService.apiCourseBook(courseId, type);
				newsDto.setCourseBook(courseBook);
				
				//获取统一忙时价格
				double initPrice = 0;
				if(!priceService.apiGetPrice(0, centerId).isEmpty()){
					 initPrice = priceService.apiGetPrice(0, centerId).get(0).getPrice();
					 initPrice=moneyService.changeMoney(initPrice);				 
				}
				
				//如果课程类型不是免费体验课程
				HashMap<String,Object> priceMap = moneyService.getPriceMap(course, studentId);
				if(priceMap != null){
					moneyBefore = (double) priceMap.get("moneyBefore");
					moneyAfter = (double) priceMap.get("moneyAfter");
					promotionList = (List<Promotion>) priceMap.get("promotionList");
					priceList = (List<Courseprice>) priceMap.get("priceList");					
				}
				
				//设置优惠前价格
				int priceType = course.getPriceType();
				if(priceType ==0 ){
					newsDto.setMoneyBefore(moneyBefore);
				}else{
					newsDto.setMoneyBefore(initPrice);
				}
				
				//设置优惠后价格
				newsDto.setMoneyExpect((moneyAfter)); 
				
				//设置优惠列表
				if(promotionList !=null ){
					for(int i=0; i<promotionList.size();i++){
						Promotion promotion = promotionList.get(i); 
						DiscountDto discount = new DiscountDto();
						if(promotion.getPromotionName() != null  && promotion.getMoney() != 0){
							discount.setId(Integer.parseInt(promotion.getId()));
							discount.setName(promotion.getPromotionName());
							discount.setMoneyCut(moneyService.changeMoney(promotion.getMoney())); 
							discount.setDescription(promotion.getName()); 	
							discountDtoList.add(discount);	
						}						
					}
				}
				newsDto.setDiscounts(discountDtoList); 	
							
				//闲时优惠金额
				double freeMoneyCut = initPrice - moneyBefore; 
				if(priceType == 0){
					newsDto.setFreeTimeDisccounts(null); 
				}else{
					freeMap = new HashMap<String,Object>();
					if(freeMoneyCut !=0 ){
						freeMap.put("moneyCut", freeMoneyCut);
						newsDto.setFreeTimeDisccounts(freeMap); 								
					}	
				}						
				
				//设置可用优惠券数码
				int couponNum = couponService.availableNum(userId, "%"+type+"%");
				newsDto.setCouponNum(couponNum);
				
				//设置优惠券实体
				if(couponId != null && !couponId.equals("")){
					Coupon coupon = couponService.selectByMemberCouponId(couponId);
					
					if(coupon != null){
	
						DiscountDto dto =new DiscountDto();
						dto.setId(Integer.parseInt(coupon.getId()));
						dto.setName(coupon.getShowName());
						dto.setDescription(coupon.getName());
						dto.setMoneyCut(initPrice);
						
						//判断优惠券类型,设置使用优惠券减少金额
						//现在暂时只有免费体验
						if(coupon.getType().equals("free") && coupon.getUseRange().contains(String.valueOf(course.getType()))){
							discountDtoList.clear();
							discountDtoList.add(dto);						
							newsDto.setMoneyExpect(initPrice-dto.getMoneyCut()); 
							newsDto.setFreeTimeDisccounts(null); 
						}
						
						//其他类型的优惠券，暂无此需求
						else if(coupon.getType().equals("deduction") && moneyAfter >= coupon.getDenomination()){
							dto.setMoneyCut(Double.valueOf(coupon.getDenomination()));						
							discountDtoList.add(dto);
							newsDto.setMoneyExpect(moneyAfter-dto.getMoneyCut());							
						}		
						
					}
				}
				
				message = "获取指定课程的预约信息成功";
				errCode = 0;				
			}else{
				message = "获取指定课程的预约信息失败,不存在该课程";
				errCode = 1;
			}
			
		} else {
			message = "获取指定课程的预约信息失败,"+checkMessage;
			errCode = 1;
		}
		return FastResponse.create().errCode(errCode).errMsg(message).obj(newsDto);

	}

	/**
	 * 课程详情/获取指定课程的预约信息
	 * @return
	 */

	@SuppressWarnings({ "unchecked", "unused" })
	@RequestMapping(value = "getCourseOrder_version2")
	public ObjResponse<OrderNewsDto> getCourseOrder_version2(HttpServletRequest request) throws Exception{
		int errCode = 0;
		String message = null;
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String centerId = request.getParameter("centerId");
		String couponId = request.getParameter("couponId");
		OrderNewsDto newsDto = new OrderNewsDto();
		List<Courseprice>  priceList = null;	
		Double moneyBefore = 0.0;	
		Course course = null;
		List<DiscountDto>  discountDtoList = new ArrayList<DiscountDto>();; 
		List<Promotion> promotionList = new ArrayList<Promotion>();
		List<HashMap<String,Object>>  promotionIdMap = null;	
		HashMap<String,Object> freeMap = null;
		double moneyAfter = 0;
		
		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL", centerId);
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");

		if (flag) {
			
			//通过id获取课程
			course = courseService.apiGetInOrOut(null, courseId);
			if(course != null){
				
				//课程预约人数
				int courseBook = orderService.apiCourseBook(courseId, null);
				newsDto.setCourseBook(courseBook);
				
				//获取统一忙时价格
				double initPrice = 0;
				if(!priceService.apiGetPrice(0, centerId).isEmpty()){
					 initPrice = priceService.apiGetPrice(0, centerId).get(0).getPrice();
					 initPrice=moneyService.changeMoney(initPrice);				 
				}
				
				//如果课程类型不是免费体验课程
				HashMap<String,Object> priceMap = moneyService.getPriceMap(course, studentId);
				if(priceMap != null){
					moneyBefore = (double) priceMap.get("moneyBefore");
					moneyAfter = (double) priceMap.get("moneyAfter");
					promotionList = (List<Promotion>) priceMap.get("promotionList");
					priceList = (List<Courseprice>) priceMap.get("priceList");					
				}
				
				//设置优惠前价格
				int priceType = course.getPriceType();
				if(priceType ==0 ){
					newsDto.setMoneyBefore(moneyBefore);
				}else{
					newsDto.setMoneyBefore(initPrice);
				}
				
				//设置优惠后价格
				newsDto.setMoneyExpect((moneyAfter)); 
				
				//设置优惠列表
				if(promotionList !=null ){
					for(int i=0; i<promotionList.size();i++){
						Promotion promotion = promotionList.get(i); 
						DiscountDto discount = new DiscountDto();
						if(promotion.getPromotionName() != null  && promotion.getMoney() != 0){
							discount.setId(Integer.parseInt(promotion.getId()));
							discount.setName(promotion.getPromotionName());
							discount.setMoneyCut(moneyService.changeMoney(promotion.getMoney())); 
							discount.setDescription(promotion.getName()); 	
							discountDtoList.add(discount);	
						}						
					}
				}
				newsDto.setDiscounts(discountDtoList); 	
							
				//闲时优惠金额
				double freeMoneyCut = initPrice - moneyBefore; 
				if(priceType == 0){
					newsDto.setFreeTimeDisccounts(null); 
				}else{
					freeMap = new HashMap<String,Object>();
					if(freeMoneyCut !=0 ){
						freeMap.put("moneyCut", freeMoneyCut);
						newsDto.setFreeTimeDisccounts(freeMap); 								
					}	
				}						
				
				//设置可用优惠券数码
				int couponNum = couponService.availableNum(userId, "%"+course.getType()+"%");
				newsDto.setCouponNum(couponNum);
				
				//设置优惠券实体
				if(couponId != null && !couponId.equals("")){
					Coupon coupon = couponService.selectByMemberCouponId(couponId);
					
					if(coupon != null){
	
						DiscountDto dto =new DiscountDto();
						dto.setId(Integer.parseInt(coupon.getId()));
						dto.setName(coupon.getName());
						dto.setDescription(coupon.getName());
						dto.setMoneyCut(initPrice);
						
						//判断优惠券类型,设置使用优惠券减少金额
						//现在暂时只有免费体验
						if((coupon.getType().equals("free")  || coupon.getType().equals("gift")) && 
								(coupon.getUseRange().contains(String.valueOf(course.getType())))){
							discountDtoList.clear();
							discountDtoList.add(dto);						
							newsDto.setMoneyExpect(initPrice-dto.getMoneyCut()); 
							newsDto.setFreeTimeDisccounts(null); 
						}
						
						//其他类型的优惠券，暂无此需求
						else if(coupon.getType().equals("deduction") && moneyAfter >= coupon.getDenomination()){
							dto.setMoneyCut(Double.valueOf(coupon.getDenomination()));						
							discountDtoList.add(dto);
							newsDto.setMoneyExpect(moneyAfter-dto.getMoneyCut());							
						}		
						
						//设置优惠券名称
						newsDto.setCouponName(coupon.getName()); 
					}
				}
				
				//预约规则
				String rule = "预约成功后，系统将按照优惠前价格进行余额的冻结#@#";
				rule += "系统将在上课前一晚10点进行扣费#@#";
				rule +="由于优惠随报名情况改变，实际优惠以扣费时点为准，敬请谅解！";
				newsDto.setRule(rule);
				 
				message = "获取指定课程的预约信息成功";
				errCode = 0;				
			}else{
				message = "获取指定课程的预约信息失败,不存在该课程";
				errCode = 1;
			}
			
		} else {
			message = "获取指定课程的预约信息失败,"+checkMessage;
			errCode = 1;
		}
		return FastResponse.create().errCode(errCode).errMsg(message).obj(newsDto);

	}	
	
	/**
	 * 课程详情/预约
	 * @return
	 */
	@RequestMapping(value = "orderCourse")
	public ObjResponse<String> orderCourse(HttpServletRequest request) throws Exception{
		int errCode = 0;
		String message = null;
		int i = 0;
		String userId = request.getParameter("userId");
		//String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String couponId = request.getParameter("couponId");
		
		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL", "NOT-NULL");
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");
		synchronized(this) {  
			if (flag) {			
				if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){		
					//课程预约操作
					Course course = courseService.apiGetInOrOut(null, courseId);
					if (course != null) {
						HashMap<String, Object> map = orderService.apiOrderCourse(course,"order",userId,studentId,String.valueOf(course.getType()),couponId);
						if(map != null){
							i = (int) map.get("id");
							String state = (String) map.get("state");
							String errMessage = (String) map.get("message");
							
							if (state.equals("true")) {
								if (i != 0) {
									message = "预约成功";
									errCode = 0;
								} else {
									message = "预约失败";
									errCode = 1;
								}
							} else{
								message = errMessage ;
								errCode = 1;
							}
						}
						
					} else {
						message = "预约失败,课程不存在";
						errCode = 1;
					}
				}else{
					message = "预约失败,请签合同";
					errCode = 1;				
				}
			} else {
				message = "预约失败,"+checkMessage;
				errCode = 1;
			}
		}

		return FastResponse.create().errCode(errCode).errMsg(message).obj("预约");
	}

	/**
	 * 课程详情/取消预约，取消等位
	 * @return
	 */
	@RequestMapping(value = "cancelCourse")
	public ObjResponse<String> cancelCourse(HttpServletRequest request) {
		int errCode = 0;
		String message = null;
		String userId = request.getParameter("userId");
		//String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");

		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL","NOT-NULL");
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");

		if (flag) {
			if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){				
				CourseOrder courseOrder = orderService.apiGetByStuAndCourse(courseId, studentId, null);
				if (courseOrder != null) {
					HashMap<String,Object>  map = orderService.cancelOrder(request);	
					int code = 1;
					if(map != null){
						code = (int) map.get("errCode");
						message = (String) map.get("errMessage");
					}
					if(code == 0){
						errCode = 0;						
					}else{
						errCode = 1;							
					}

				} else {
					message = "取消失败，不存在该订单";
					errCode = 1;
				}		
			}else{
				message = "取消预约失败，请签合同";
				errCode = 1;
			}

		} else {
			message = "取消预约失败,"+checkMessage;
			errCode = 1;
		}
		
		return FastResponse.create().errCode(errCode).errMsg(message).obj("取消预约");
	}

	/**
	 * 课程详情/加入等位
	 * @return
	 */
	@RequestMapping(value = "waitCourse")
	public ObjResponse<String> waitCourse(HttpServletRequest request) throws Exception{
		int errCode = 0;
		String message = null;
		String userId = request.getParameter("userId");
		//String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		String couponId = request.getParameter("couponId");
		int i = 0;
		
		// 参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL", "NOT-NULL");
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");
		
		if (flag == true) {
			if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){			
				//加入排队操作
				Course course = courseService.apiGetInOrOut(null, courseId);
				if (course != null) {
					HashMap<String, Object> map = orderService.apiOrderCourse(course,"queue",userId,studentId,String.valueOf(course.getType()),couponId);
					i = (int) map.get("id");
					String state = (String) map.get("state");
					String errMessage = (String) map.get("message");
					
					if (state.equals("true")) {
						if (i != 0) {
							message = "排队成功";
							errCode = 0;
						} else {
							message = "排队失败";
							errCode = 1;
						}
					} else {
						message = errMessage;
						errCode = 1;
					}
	
				} else {
					message = "排队失败,课程不存在";
					errCode = 1;
				}
			}else{
				message = "排队失败,请签合同";
				errCode = 1;
			}
		} else {
			message = "排队失败,"+checkMessage;
			errCode = 1;
		}

		return FastResponse.create().errCode(errCode).errMsg(message).obj("排队");
	}

	/**
	 * 课程详情/请假
	 * @return
	 */
	@RequestMapping(value = "leaveCourse")
	public ObjResponse<String> leaveCourse(HttpServletRequest request) {
		int errCode = 0;
		String message = null;
		String userId = request.getParameter("userId");
		//String type = request.getParameter("type");
		String studentId = request.getParameter("studentId");
		String courseId = request.getParameter("courseId");
		
		//参数校验
		HashMap<String,Object> checkMap = orderService.apiCheckParameter(courseId, studentId, userId, "NOT-NULL", "NOT-NULL");
		boolean flag = (boolean) checkMap.get("flag");
		String checkMessage = (String) checkMap.get("errMessage");
		
		if (flag == true) {
			if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){				
				CourseOrder courseOrder = orderService.apiGetByStuAndCourse(courseId, studentId, null);
				if(courseOrder != null && !courseOrder.getState().equals("leaved")){							
					//请假操作							
					HashMap<String,Object>  map  = orderService.leaveCourse(request,"app");	
					if(map != null){
						errCode = (int) map.get("errCode");
						message = (String) map.get("message");
					}			
				}else{
					message = "请假失败,不存在该订单";
					errCode = 1;
				}
			}else{
				message = "请假失败，请签合同";
				errCode = 1;				
			}
		} else {
			message = "请假失败,"+checkMessage;
			errCode = 1;
		}
		
		return FastResponse.create().errCode(errCode).errMsg(message).obj("请假");
	}
	
}
